<script setup>

import MyNav from "@/components/MyNav.vue";
import {getResponseData} from "@/util";
import {listApi} from "@/api/RoleApi";
import {getRolesApi, updateRolesApi} from "@/api/EmpApi";
import {onBeforeMount, onMounted, ref, shallowRef} from "vue";
import router from "@/router";
import {ElMessage} from "element-plus";

let empId = router.currentRoute.value.query['empId'];
let myRoles = ref([]);
let allRoles = ref([]);
let valueKeys = ref([]);

// 获取全部角色列表 + 当前员工的角色列表
function listData() {

  // 获取全部角色列表
  listApi().then(res => {
    let allRolesData = getResponseData(res);
    if (allRolesData) {
      allRoles.value = allRolesData;

      // 获取我的角色列表
      getRolesApi(empId).then(res => {
        let myRolesData = getResponseData(res);
        if (myRolesData) {
          myRoles.value = myRolesData;

          // 构建key数组（清空数组，防止叠加）
          for (let i in myRolesData) {
            valueKeys.value.push(myRolesData[i]['id']);
          }
        }
      })
    }
  });
}

//确认修改角色
async function updateRoles() {
  //获取当前登录的员工
  let loginEmp = JSON.parse(sessionStorage.getItem('loginEmp'));

  let res = await updateRolesApi({
    'id': empId,
    'roleIds': valueKeys.value
  });
  let data = getResponseData(res);
  if(data){
    ElMessage.success('角色列表更新成功!');
    //若修改的是当前登陆的员工,则跳入登陆界面
    if (loginEmp['id'] === empId) {
      ElMessage.success('修改了当前登录的员工信息，请重新登录！');
      setTimeout(() => router.push('/'), 1000);
    }
    // 否则重新分页
    else {
      setTimeout(()=> router.push('/Emp'),1000);
    }
  }
}
onBeforeMount(() => listData());

</script>

<template>
  <div class="transfer-body">

    <my-nav :items="[
      {'icon': 'User', 'label': '员工管理'},
      {'icon': 'User', 'label': '员工列表', 'url': '/ums/Emp'},
      {'icon': 'User', 'label': '角色列表'},
    ]"/>

    <el-divider/>

    <el-transfer v-if="valueKeys" v-model="valueKeys" :data="allRoles"
                 filterable filter-placeholder="输入关键字"
                 :titles="['全部可选项', '当前已选项']"
                 :props="{'key': 'id', 'label': 'title'}"
                 :button-texts="['移除', '添加']"/>
    <el-divider/>

    <el-button class="update-roles-btn" type="primary" @click="updateRoles">确认修改</el-button>
  </div>
</template>

<style scoped lang="scss">
.transfer-body {
  text-align: center;

  .update-roles-btn {
    width: 100%; // 宽度
  }
}

/* 修改EL穿梭框高度 */
:deep(.el-transfer-panel), :deep(.el-transfer-panel__body) {
  height: 500px; // 高度
}
</style>